<template>
  <div class="info-form">
    <el-form ref="infoForm" :model="infoForm" size="small" label-width="100px">
      <el-form-item label="课程视频"  v-loading='videoLoading'>
        <!-- :file-list="fileList" -->
        <div class="videoBox" v-if='infoForm.contentUrl' >
            <div class="im-button" @click="removeVideo">
                <div class="im-close"></div>
                <div class="im-close1"></div>
            </div>
            <video :src="infoForm.contentUrl" width="100%"  controls="controls"  id="videoDom"></video>
        </div>
        <!-- /api/qiniu/upload -->
        <!-- :http-request="sliderRequest" -->
         <!-- :before-upload='videoBefore' -->
        <el-upload   v-else class="upload-demo" :http-request="sliderRequest"  action="http://test.queenstar.vip/qiniu"  :data='{token:videoToken,key:videoKey}' :on-change='videoBefore' :on-remove='removeVideo' :limit="1"  name="file" :accept='infoForm.type==1?"audio/*":"video/*"' :on-success='videoUpload'>
          <el-button size="small" type="primary">点击上传</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>

      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="infoForm.type">
          <el-radio :label="2">视频</el-radio>
          <el-radio :label="1">音频</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="课程封面">
        <uploadImage :isCompress="true" ref="uploadImage" v-model="infoForm.coverUrl" :photo="[infoForm.coverUrl]" :img="infoForm.coverUrl"
          v-on:addImage="addImage" :limit=1 v-on:removeImage="removeImage"></uploadImage>
      </el-form-item>

      <el-form-item label="章节名称" prop="sectionName" :rules="[{
                    required: true, message: '章节名称不能为空', trigger: 'blur'
                  },{min: 2, max: 20, message: '章节名称长度在2 到 20 个字符', trigger: 'blur'}]">
        <el-input maxlength="20" clearable v-model="infoForm.sectionName" size="small" placeholder="请输入章节名称" />
      </el-form-item>
      <el-form-item label="排序" prop="sort" >
        <el-input   clearable v-model="infoForm.sort"  type="number" size="small" placeholder="请输入排序"/>
      </el-form-item>
    </el-form>
    <div style="text-align: center">
      <el-button icon="el-icon-document-add" :loading="addBtnLoading" type="primary" size="medium" @click="submitForm('infoForm')">提交
      </el-button>
      <el-button icon="el-icon-back" style="margin-left: 15px" size="medium" @click="closeWin('infoForm')">关闭
      </el-button>
    </div>
  </div>
</template>

<script>
  import gzhApi from '@/api/gzh/video'
  import uploadImage from '@/components/newUploadImage'
import axios from 'axios'
import * as qiniu from 'qiniu-js'
  export default {
    name: "member",
    data() {
      // 手机号验证
      var phoneReg = /^1\d{10}$/
      var validatePhone = (rule, value, callback) => {
        if (value) {
          if (!phoneReg.test(value)) {
            callback(new Error('请输入正确手机号码'));
          } else {
            callback();
          }
        } else {
          callback(new Error('手机号码必填'));
        }
      };
      return {
        videoLoading:false,
        uillUpdateImg: false,
        videoToken:'',
        videoKey:'',
        paramsList: [



        ],
        addBtnLoading: false,
        // 手机号验证
        validatePhone: validatePhone,
      }
    },
    props: {
      infoForm: {
        type: Object,
        default () {
          return {};
        }
      },
    },
    created() {},
    mounted() {
        this.getToken();

    },
    components: {
      uploadImage
    },
    methods: {
      pauseVideo(){
        document.getElementById('videoDom').pause();
      },
      sliderRequest(upload){
        this.videoKey=new Date().getTime()+upload.file.name
          console.log(upload.file.name,'1111')
          var self_=this;
          gzhApi.qiToken().then(res=>{
              console.log(res)
              if(res.code==200){
                  self_.videoToken=res.data;
                   const formData = new FormData() // 创建FormData对象
                            // 添加相关上传参数
                       formData.append('file', upload.file)
                       formData.append('key', self_.videoKey) // key 文件名处理，这样的话七牛会识别文件时什么类型
                       formData.append('token',self_.videoToken)
                       console.log(upload.file)
              const observable = qiniu.upload(upload.file, self_.videoKey, self_.videoToken)
              const subscription = observable.subscribe(()=>{},()=>{},(e)=>{
                  console.log(e)
                  this.infoForm.contentUrl = `http://qhd4en5tw.hn-bkt.clouddn.com/${e.key}`;
                  this.videoLoading=false;
                  this.getToken();
              }) // 上传开始
                  // axios.post('http://test.queenstar.vip/qiniu',formData,{
                  //       headers: {
                  //               'Access-Control-Allow-Origin': '*',
                  //               'Content-Type': 'multipart/form-data'
                  //           }

                  // }).then(res=>{

                  //       console.log('上传完成',res);
                  // });


              }
          })


      },
      removeVideo(){
        this.infoForm.contentUrl = '';
      },
      getToken(){
        var self_=this;
          gzhApi.qiToken().then(res=>{
              console.log(res)
              if(res.code==200){
                  self_.videoToken=res.data;
              }
          })
      },
      videoBefore(e){
            console.log(e)
            this.videoKey=new Date().getTime()+e.name
            this.videoLoading=true;
      },
      videoUpload(e,file){
        console.log(e)
        // console.log(file.raw)

      },
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if(this.infoForm.contentUrl==''){
            this.$message({
              message:'请上传课程视频'
            });
            return false;
          }

          if(this.infoForm.coverUrl==''){
            this.$message({
              message:'请上传课程封面'
            });
            return false;
          }

          var parmseData = this.infoForm;
          if (valid) {
            let method = 'courseJieAdd'
            if (this.infoForm.id) {
              method = 'courseJieEdit'
            } else {
              parmseData.status = 1;
            }

            // alert(document.getElementById('videoDom').duration)
            parmseData.duration=document.getElementById('videoDom').duration;
            this.addBtnLoading = true
            gzhApi[method](parmseData).then(res => {
              this.addBtnLoading = false
              this.$refs[formName].resetFields()
              this.$message({
                type: 'success',
                message: this.infoForm.id ? '修改成功' : '添加成功'
              })
              if (this.infoForm.id) {
                // 编辑
                this.$emit('submit', 1)
              } else {
                // 添加
                this.$emit('submit', 0)
              }
              // 调动关闭窗体方法
              this.$emit('closeWin')
            }).catch(e => {
              this.addBtnLoading = false
            })
          }
        })
      },
      removeImage(){
        this.infoForm.coverUrl = ''
      },
      // 添加图片
      addImage(...data){
        console.log(data)
        this.infoForm.coverUrl = data[0]
      },
      // 关闭窗体
      closeWin() {
        this.$refs['infoForm'].resetFields()
        this.$emit('closeWin')
      }
    }
  }
</script>

<style lang="less">
  .videoBox{
    width: 30%;
    position: relative;
    overflow: hidden;
  }
  .ql-editor {
    max-height: 45vh;
    overflow: scroll;
  }

  .el-dialog__body {
    max-height: 65vh;
    overflow: scroll;
  }
  .videoBox .im-button {
    position: absolute;
    top: -14px;
    right: -18px;
    width: 40px;
    z-index: 100;
    height: 40px;
    cursor: pointer;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, .5);
    opacity: 0;
  }
  .videoBox:hover .im-button {
    opacity: 1;
  }
  .im-button:hover{
    cursor: pointer;
  }
  .videoBox .im-close {
    transform: rotate(-45deg);
    line-height: 0px;
    left: 6px;
    bottom: 13px;
    display: inline-block;
    width: 15px;
    height: 2px;
    background: #fff;
    position: absolute;
  }
  .videoBox .im-close1 {
    left: 5px;
    bottom: 13px;
    display: inline-block;
    width: 15px;
    height: 2px;
    background: #fff;
    position: absolute;
    transform: rotate(45deg);
  }
</style>
